#include <stdio.h>
#include <pthread.h>
int data[5];//仓库
int size=0;//当前库存
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;//静态初始化互斥锁;
pthread_cond_t full = PTHREAD_COND_INITIALIZER;//初始化条件量:仓库满;
pthread_cond_t empty = PTHREAD_COND_INITIALIZER;//初始化条件量：仓库空;
//输出仓库的库存
void print(){
	int i;
	printf("当前库存为：");
	printf("\n");
	for(i=1;i<=size;i++){
	  printf("%d",data[i]);
	}
	printf("\n");
}
//生产者线程
void* producer(){
	
    for(int i=1;i<20;i++){
	pthread_mutex_lock(&mutex);//互斥锁上锁
	while(size==5){//仓库满了
		printf("仓库满了");
		printf("\n");
		printf("等待消费者消费产品");
		pthread_cond_wait(&full,&mutex);//阻塞生产进程
		
		}
	
	size=size+1;
	data[size]=i;
	printf("生产者生产商品:   %d size:%d",data[size],size);
	printf("\n");

	print();
	pthread_cond_broadcast(&empty);
	pthread_mutex_unlock(&mutex);//释放锁
	sleep(2);
	}

}
//消费者线程
void* customer(void *p){
	for(int i=1;i<20;i++){
	pthread_mutex_lock(&mutex);//互斥锁上锁
	while(size==0){//仓库空了
		printf("仓库为空");
		printf("\n");
		printf("等待生产者生产产品");
		pthread_cond_wait(&empty,&mutex);//阻塞消费进程
		
		}
	printf("消费者消费商品:   %d size:%d",data[size],size);
	 printf("\n");
	size=size-1;
	print();
	pthread_cond_broadcast(&full);
	pthread_mutex_unlock(&mutex);//释放锁
	sleep(2);
	}
}
int main(){
	pthread_t pro,cus;
	pthread_create(&pro,0,producer,0);
	pthread_create(&cus,0,customer,0);
	pthread_join(pro,0);
	pthread_join(cus,0);
	pthread_mutex_destroy(&mutex);
}
